<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible && !detailListInfo.visible && !modifyInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList"> </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="false"
        :tab-index="true"
        :highlightRow="true"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('putShelfTask:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo }}</span
          >
          <span v-else class="slip-edit">{{ scope.row.orderNo }}</span>
        </template>
      </table-container>
    </div>
    <detail
      v-if="detailInfo.visible"
      :table-id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />

    <!-- 明细 -->
    <detail-list
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detail-list>
    <!-- 导出 -->
    <page-dialog
      v-show="excelOrPrintDialogInfo.visible"
      :title="excelOrPrintDialogInfo.title"
      v-model:visible="excelOrPrintDialogInfo.visible"
      :width="excelOrPrintDialogInfo.width"
      :bt-loading="excelOrPrintDialogInfo.btLoading"
      :bt-list="excelOrPrintDialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ excelOrPrintDialogInfo.msg }}：
        </div>
        <el-radio-group v-model="excelOrPrintDialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <AddByStorageStockOrder
      v-if="addStorageStockDialog.visible"
      v-model:showDialog="addStorageStockDialog.visible"
      :checkBox="false"
      :highlightRow="true"
      @callback="addStorageStockBack"
    />
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
      :tableRow="modifyInfo.tableRow"
      @returnModify="returnModify"
    />
    <select-users
      v-if="userInfo.visible"
      @callback="save"
      v-model:showDialog="userInfo.visible"
      :query="userInfo.query"
      :checkBox="false"
      :saveEmpty="false"
      :api="userInfo.api"
      :highlightRow="true"
    />
  </div>
</template>

<script setup name="putShelfTask">
import { fatchTemplateByCode, getRrgUserPage } from '@/api/base.js'
import {
  getPutShelfCustomizeList,
  transferPutShelfTask,
  putShelfTaskCancel,
  putShelfTaskStore,
  putShelfTaskStop,
  exportExcelPutShelfTaskOrder,
  printPutShelfTaskOrderList,
  removePutShelfTask,
  putShelfTaskReceive,
} from '@/api/wms.js'
import { getDepotAll } from '@/api/core'
import Detail from './details'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import DetailList from './detailList'
import AddByStorageStockOrder from './addByStorageStockOrder'
import Modify from './modify'
import { revokeAssetTransfer } from '@/api/asset'

const { proxy } = getCurrentInstance()

//导出提示相关配置
const excelOrPrintDialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: excelOrPrintHandleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})

const modifyInfo = ref({
  visible: false,
  id: '',
  title: '新增上架任务',
  tableRow: {},
})

const userInfo = ref({
  visible: false,
  api: getRrgUserPage,
  id: '',
  query: {
    idNotIn: '',
    depotAuth: '',
    status: 1,
    isTransfer: 1,
  },
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'wms_put_shelf_task',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    // {
    //   type: 'button',
    //   label: '入库单导入',
    //   event: storageStockImport,
    //   show: proxy.$permission('putShelfTask:storageStockImport'),
    // },
    {
      label: '打印',
      type: 'button',
      event: print,
      show: proxy.$permission('putShelfTask:printOrderList'),
    },
    {
      label: '导出excel',
      type: 'button',
      event: excel,
      show: proxy.$permission('putShelfTask:excelOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: proxy.update,
        show: proxy.$permission('putShelfTask:update'),
        ifRender: function (row) {
          return row.status === 1 && row.sourceOrderId === -2
        },
      },
      {
        label: '接单',
        event: orderReceive,
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '转交',
        event: transfer,
        show: proxy.$permission('putShelfTask:transfer'),
        ifRender: function (row) {
          return row.status === 2 || row.status === 3
        },
      },
      {
        label: '取消',
        event: doCancel,
        show: proxy.$permission('putShelfTask:cancel'),
        ifRender: function (row) {
          return (
            row.status === 2 ||
            row.status === 3 ||
            row.status === 6 ||
            row.status === 7
          )
        },
      },
      {
        label: '入库',
        event: doStore,
        show: proxy.$permission('putShelfTask:store'),
        ifRender: function (row) {
          return row.onlyOnePendStockTask === 1 && row.status === 7
        },
      },
      {
        label: '中止',
        event: doStop,
        show: proxy.$permission('putShelfTask:stop'),
        ifRender: function (row) {
          return row.status === 3
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('putShelfTask:delete'),
        ifRender: function (row) {
          return row.status === 1 && row.sourceOrderId === -2
        },
      },
    ],
  },
})
const detailListInfo = ref({ visible: false })
const detailInfo = ref({
  visible: false,
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const addStorageStockDialog = ref({
  visible: false,
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'putShelfTask' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.orderNo = val.orderNo
                    detailInfo.value.tableId = val.orderId
                    sessionStorage.setItem('storeRowId', val.orderId)
                    console.log(detailInfo.value, 11111111)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'wms_put_shelf_task_status',
      show: false,
      hidden: true,
    },
    depotName: {
      label: '出库仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '1',
        isCargoSpaceManage: 1,
      },
      api: getDepotAll, //getDeptAll, getDepotAll, getSupplierAll
      show: false,
      hidden: true,
    },
    locationTypeValue: {
      label: '货位属性',
      value: 'locationTypeValue',
      asValue: 'locationType',
      componentType: 'select-model',
      code: 'goods_location_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function storageStockImport() {
  //入库单导入
  addStorageStockDialog.value.visible = true
}
function addStorageStockBack(data) {
  if (data && data.id) {
    proxy.$nextTick(() => {
      modifyInfo.value.visible = true
      modifyInfo.value.tableRow = data
    })
  }
}
function returnModify() {
  if (modifyInfo.value.exportId) {
    getList()
  } else {
    search()
  }
}
function pageInfo(obj) {
  page.value = obj
}
//打印
function print() {
  excelOrPrintDialogInfo.value.visible = true
  excelOrPrintDialogInfo.value.type = 'print'
  excelOrPrintDialogInfo.value.msg = '请选择当数据打印范围'
  excelOrPrintDialogInfo.value.btList[1].label = '打印'
  excelOrPrintDialogInfo.value.flag = true
}
//导出
function excel() {
  excelOrPrintDialogInfo.value.visible = true
  excelOrPrintDialogInfo.value.type = 'excel'
  excelOrPrintDialogInfo.value.msg = '请选择数据导出范围'
  excelOrPrintDialogInfo.value.btList[1].label = '导出'
  excelOrPrintDialogInfo.value.flag = true
}
//打印或导出Excel
function checkConfirm() {
  if (excelOrPrintDialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (excelOrPrintDialogInfo.value.type === 'print') {
    printList()
  }
  excelOrPrintDialogInfo.value.visible = false
  excelOrPrintDialogInfo.value.msg = ''
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: excelOrPrintDialogInfo.value.flag,
  }
  exportExcelPutShelfTaskOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'putShelfTask:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, excelOrPrintDialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  printPutShelfTaskOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function excelOrPrintHandleClose() {
  excelOrPrintDialogInfo.value.visible = false
}
//接单
function orderReceive(row) {
  putShelfTaskReceive(row).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//转交
function transfer(row) {
  userInfo.value.visible = true
  userInfo.value.id = row.id
  userInfo.value.query.idNotIn = row.putShelfUser || ''
  userInfo.value.query.depotAuth = row.depotId
}
//转交保存
function save(data) {
  let params = {
    id: userInfo.value.id,
    putShelfUser: data.id,
  }
  transferPutShelfTask(params).then((resp) => {
    if (resp && resp.success) {
      getCustomize()
    }
  })
}
// 入库
function doStore(row) {
  proxy
    .$confirm('确认入库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      putShelfTaskStore(row.id).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
//取消
function doCancel(row) {
  proxy
    .$confirm('确认取消吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      putShelfTaskCancel(row.id).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
// 中止
function doStop(row) {
  proxy
    .$confirm('确认中止吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      putShelfTaskStop(row.id).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}

async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}

function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  removePutShelfTask(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: 'putShelfTaskList-com.slip.spd.entity.vo.wms.WmsPutShelfTaskVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getPutShelfCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
